package com.graduation.clientback.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.graduation.clientback.common.R;
import com.graduation.clientback.domain.TbStep;
import com.graduation.clientback.domain.TbTask;
import com.graduation.clientback.domain.TbUser;
import com.graduation.clientback.domain.Work;
import com.graduation.clientback.domain.vo.TbTaskVo;
import com.graduation.clientback.service.StepService;
import com.graduation.clientback.service.TaskService;
import com.graduation.clientback.service.TbUserService;
import com.graduation.clientback.service.WorkService;
import com.graduation.clientback.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private StepService stepService;

    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private WorkService workService;

    /**
     * 申请选课
     * @param tbTask
     * @return
     */
    @Transactional
    @PostMapping("/add")
    public R<String> add(@RequestBody TbTask tbTask) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userCode = (String) claims.get("code");
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbUser::getUserCode, userCode);
        TbUser tbUser = tbUserService.getOne(queryWrapper);
        if(tbUser == null) {
            return R.error("学生不存在");
        }
        LambdaQueryWrapper<Work> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Work::getStuId, tbUser.getUserId());
        if(workService.count(queryWrapper2) > 0) {
            return R.error("已经有申请成功的毕设，快去完成吧");
        }
        LambdaQueryWrapper<TbTask> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(TbTask::getStuId, tbUser.getUserId());
        queryWrapper1.eq(TbTask::getStatus, 1).or().eq(TbTask::getStatus, 2);
        if(taskService.count(queryWrapper1) > 0) {
            return R.error("已申请选课,请等待审核");
        }
        tbTask.setStuId(tbUser.getUserId());
        tbTask.setTchId(tbUser.getTchId());
        tbTask.setCreateTime(LocalDateTime.now());
        tbTask.setUpdateTime(LocalDateTime.now());
        taskService.save(tbTask);
        TbStep tbStep = new TbStep();
        log.info("Task saved with taskId: {}", tbTask.getTaskId());
        tbStep.setStepName("提交申请");
        tbStep.setStepDesc("提交申请");
        tbStep.setCreateTime(LocalDateTime.now());
        tbStep.setUpdateTime(LocalDateTime.now());
        tbStep.setTaskId(tbTask.getTaskId());
//        tbStep.setOperateName(tbUser.getUserName());
        stepService.save(tbStep);
        return R.success("申请成功");
    }

    /**
     * 查看选课申请列表
     * @return
     */
    @GetMapping("/list")
    public R<List<TbTaskVo>> list(TbTask task) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userCode = (String) claims.get("code");
        Integer userId = (Integer) claims.get("id");
        String userType = userCode.substring(0, 3);
        LambdaQueryWrapper<TbTask> queryWrapper = new LambdaQueryWrapper<>();
        if("stu".equals(userType)) {
            queryWrapper.eq(TbTask::getStuId, userId);
        } else {
            queryWrapper.eq(TbTask::getTchId, userId);
            if(task.getStatus() == 1) {
                queryWrapper.eq(TbTask::getStatus, task.getStatus());
            } else {
                queryWrapper.ne(TbTask::getStatus, 1);
            }
        }
        queryWrapper.orderByDesc(TbTask::getUpdateTime);
        List<TbTask> list = taskService.list(queryWrapper);
        List<TbTaskVo> collect = list.stream().map(item -> {
            TbTaskVo tbTaskVo = new TbTaskVo();
            BeanUtils.copyProperties(item, tbTaskVo);
            log.info("tbTaskVo: {}", tbTaskVo);
            LambdaQueryWrapper<TbUser> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(TbUser::getUserId, item.getStuId());
            TbUser stu = tbUserService.getOne(queryWrapper1);
            tbTaskVo.setStu(stu);
            return tbTaskVo;
        }).collect(Collectors.toList());
        return R.success(collect);
    }

    /**
     * 获取选课申请详情
     * @param taskId
     * @return
     */
    @GetMapping("/detail")
    public R<TbTaskVo> detail(Integer taskId) {
        TbTask task = taskService.getById(taskId);
        TbTaskVo taskVo = new TbTaskVo();
        BeanUtils.copyProperties(task, taskVo);
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbUser::getUserId, task.getStuId());
        TbUser stu = tbUserService.getOne(queryWrapper);
        taskVo.setStu(stu);
        return R.success(taskVo);
    }

    /**
     * 获取选课申请对应的进度条
     * @param taskId
     * @return
     */
        @GetMapping("/steps")
    public R<List<TbStep>> steps(Integer taskId) {
        LambdaQueryWrapper<TbStep> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbStep::getTaskId, taskId);
        List<TbStep> list = stepService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 导师审核
     * @param step
     * @return
     */
    @PutMapping("/tch")
    public R<String> tch(@RequestBody TbStep step) {
        TbTask task = taskService.getById(step.getTaskId());
        LambdaQueryWrapper<TbUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbUser::getUserId, task.getTchId());
        TbUser tch = tbUserService.getOne(queryWrapper);
        step.setOperateName(tch.getUserName());
        step.setStepName("导师审核");
        step.setCreateTime(LocalDateTime.now());
        step.setUpdateTime(LocalDateTime.now());
        stepService.save(step);
        if(step.getStatus() == 1) {
            task.setStatus(2L);
        } else {
            task.setStatus(3L);
        }
        taskService.updateById(task);
        return R.success("审核成功");
    }

    /**
     * 监管人员审核
     * @param step
     * @return
     */
    @PutMapping("/monitor")
    public R<String> stu(@RequestBody TbStep step) {
        TbTask task = taskService.getById(step.getTaskId());
        step.setOperateName("监管人员");
        step.setStepName("监管人员审核");
        step.setCreateTime(LocalDateTime.now());
        step.setUpdateTime(LocalDateTime.now());
        step.setStepDesc("已核实，情况属实，审核通过");
        stepService.save(step);
        if(step.getStatus() == 1) {
            task.setStatus(4L);
        } else {
            task.setStatus(3L);
        }
        taskService.updateById(task);
        return R.success("审核成功");
    }

}
